package huisu;

import javax.sound.midi.Soundbank;
import java.util.Arrays;

public class Queens8Question {
    /***
     *全局或成员变量,下标表示行,值表示queen存储在哪一列
     */
    private static final int [] result=new int[8];

    public static  void cal8Queens(int row){
        if(row==8){
//            printQueens(result);
            System.out.println(Arrays.toString(result));
            return;
        }
        for (int col = 0; col < 8; col++) {
            if(isok(row,col)){
                result[row]=col;
                cal8Queens(row+1);
            }
        }
    }

    public static boolean isok(int row ,int column){
        int leftup = column - 1, rightup = column + 1;
            // 逐行往上考察每一行
        for (int i = row-1; i >= 0; --i) {
            if (result[i] == column) {
                return false; // 第i行的column列有棋子吗？
            }
            if (leftup >= 0&&result[i] == leftup) {// 考察左上对角线：第i行leftup列有棋子吗？
                 return false;
            }
            if (rightup < 8&&result[i] == rightup) { // 考察右上对角线：第i行rightup列有棋子吗？
                 return false;
            }
            --leftup; ++rightup;
        }
        return true;
    }
    public static void printQueens(int[] result){
        for (int row = 0; row < 8; row++) {
            for (int col = 0; col < 8; col++) {
               if(result[row]==col){
                   System.out.print("Q");
               }else{
                   System.out.print("*");
               }
            }
            System.out.println();
        }
        System.out.println();
    }
    public static void main(String[] args) {
        cal8Queens(0);
    }
}
